; BierChat Functies

;Maak de brushes 
brush(#C0Brush) = CreateSolidBrush_(RGB(255, 255, 255))        
brush(#C1Brush) = CreateSolidBrush_(RGB(173, 216, 230))        
brush(#C2Brush) = CreateSolidBrush_(RGB(255, 255, 255))        
brush(#SelectedBrush) = CreateSolidBrush_(RGB(135, 206, 250))   
  
Declare.s IRCEnumNames(Channel.s)
Declare ParseIRCData()


Global Dim Arg.s(50)

Procedure ParseIRCData()
  
    *Buffer = AllocateMemory(1024)
    ReceiveNetworkData(ConnectionID, *Buffer, 1024)
    
    txt.s = PeekS(*Buffer)
    FreeMemory(*Buffer)
    
    For i = 1 To CountString(txt.s," ") 
      arg(i) = StringField(txt.s,i," ")
    Next
    
    If arg(1) = "PING"
      SendNetworkString(ConnectionID,ReplaceString(txt.s,"PING :", "PONG :",0)+Chr(13)+Chr(10))
    EndIf
    
    
    Select arg(2)
        
      Case Str(#RPL_AWAY)
        ; Doe maar iets
        
      Case Str(#RPL_BANLIST)
        ; Doe nog maar iets
    EndSelect
    
  
EndProcedure


Procedure CreateUserList()
  
  ClearGadgetItems(2)   
  
    Shared Names.s
    
    Names.s = IRCEnumNames(Channel.s)
    Login = 1
        
    For k=1 To CountString(Names, " ")  
      Cur.s = StringField(Names, k, " ")
      If Len(Cur) > 1
        AddGadgetItem(2, -1, Cur)
      EndIf
    Next
  
EndProcedure

  
  
Procedure ChatCallBack(hwnd, msg, wParam, lParam) 
  result = #PB_ProcessPureBasicEvents 
  Select msg 
    Case #WM_NOTIFY 
      *nmhdr.NMHEADER = lParam 
       
      If *nmhdr\hdr\code = #HDN_ITEMCHANGING  And *nmhdr\iItem = 0 
        result = #True 
      EndIf 
      *lvCD.NMLVCUSTOMDRAW = lParam 
      If *lvCD\nmcd\hdr\hwndFrom=GadgetID(0) And *lvCD\nmcd\hdr\code = #NM_CUSTOMDRAW    
        Select *lvCD\nmcd\dwDrawStage 
          Case #CDDS_PREPAINT 
            result = #CDRF_NOTIFYITEMDRAW 
          Case #CDDS_ITEMPREPAINT 
            result = #CDRF_NOTIFYSUBITEMDRAW; 
          Case #CDDS_ITEMPREPAINT | #CDDS_SUBITEM 
            thisItem = *lvCD\nmcd\dwItemSpec 
         
            subItemRect.RECT\left = #LVIR_LABEL 
            subItemRect.RECT\top = *lvCD\iSubItem 
        
            SendMessage_(GadgetID(0), #LVM_GETSUBITEMRECT, thisItem, @subItemRect) 
            subItemText$ = GetGadgetItemText(0, *lvCD\nmcd\dwItemSpec, *lvCD\iSubItem) 
            sitLen = Len(subItemText$) 
            Select *lvCD\iSubItem 
              Case 0 
;                 
                lvFlags =  #DT_END_ELLIPSIS | #DT_WORDBREAK
;             
                If GetGadgetState(0) = thisItem 
                  
                  FillRect_(*lvCD\nmcd\hdc, subItemRect, brush(#SelectedBrush)) 
                Else 
                 
                  FillRect_(*lvCD\nmcd\hdc, subItemRect, brush(#C0Brush)) 
                EndIf 
;                
                SetTextColor_(*lvCD\nmcd\hdc, RGB(0, 0, 0)) 
              Case 1 
               
                 
;                 lvFlags = #DT_END_ELLIPSIS | #DT_SINGLELINE | #DT_VCENTER 
;                 If GetGadgetState(0) = thisItem 
;                
;                   FillRect_(*lvCD\nmcd\hdc, subItemRect, brush(#SelectedBrush)) 
;                 Else 
;                
;                   FillRect_(*lvCD\nmcd\hdc, subItemRect, brush(#C1Brush)) 
;                 EndIf 
;              
;                 SetTextColor_(*lvCD\nmcd\hdc, RGB(0, 0, 0)) 
              Case 2 
;                 lvFlags =  #DT_END_ELLIPSIS | #DT_WORDBREAK
;             
;                 If GetGadgetState(0) = thisItem 
;                   
;                   FillRect_(*lvCD\nmcd\hdc, subItemRect, brush(#SelectedBrush)) 
;                 Else 
;                  
;                   FillRect_(*lvCD\nmcd\hdc, subItemRect, brush(#C2Brush)) 
;                 EndIf 
; ;                
;                 SetTextColor_(*lvCD\nmcd\hdc, RGB(0, 0, 0)) 
            EndSelect 
             
            subItemRect\left +3 
            subItemRect\right -3 
            subItemRect\bottom -3 
        
            DrawText_(*lvCD\nmcd\hdc, subItemText$, sitLen, subItemRect, lvFlags) 
            result = #CDRF_SKIPDEFAULT 
        EndSelect 
      EndIf 
  EndSelect 
  ProcedureReturn result 
EndProcedure 


Procedure CreateMAinWindow()
  If OpenWindow(0, 216, 0, 450, 300,"BierIRC  "+Channel.s, #PB_Window_MinimizeGadget | #PB_Window_SizeGadget | #PB_Window_MaximizeGadget | #PB_Window_SystemMenu | #PB_Window_TitleBar)
      
      AddKeyboardShortcut(0, #PB_Shortcut_Return, 1)
      LoadFont(0,"verdana",8)
      StringGadget(1, 10, 270, 430, 20, "")  
      
     ; ListViewGadget(0, 10, 10, 280, 250)  
      ListIconGadget(0,10,10,280,250,"alles",800, #PB_ListIcon_FullRowSelect|#LVS_NOCOLUMNHEADER)
       
      
      ListViewGadget(2, 290, 10, 150, 250)  
      
      SetGadgetFont(0,FontID(0))
      SetGadgetFont(2,FontID(0))
      
       
      ;Maak de ListIconGadget groter voor multiline :)
      imageList = ImageList_Create_(1, 30, #ILC_COLOR32, 0, 32) 
      SendMessage_(GadgetID(0), #LVM_SETIMAGELIST, #LVSIL_SMALL, imageList) 
      
      SetWindowCallback(@ChatCallback()) 
   EndIf

EndProcedure


Procedure IRCConnect(Server.s, Port.l)
  Connection = OpenNetworkConnection(Server, Port)
  If Connection <> 0
    ConnectionID = Connection
  EndIf
  ProcedureReturn Connection
EndProcedure

Procedure IRCUseConnection(Connection)
  ConnectionID = Connection
EndProcedure

Procedure IRCLogin(Server.s, Name.s, Pass.s)
  SendNetworkString(ConnectionID,"USER "+ReplaceString(Name, " ", "_")+" localhost "+Server+" :Bierdopje"+Chr(13)+Chr(10)) 
  SendNetworkString(ConnectionID,"NICK "+ReplaceString(Name, " ", "_")+Chr(13)+Chr(10))
  If Pass <> ""
    SendNetworkString(ConnectionID,"PRIVMSG NickServ :IDENTIFY "+Pass+Chr(13)+Chr(10))
  EndIf
EndProcedure

Procedure IRCChangeNick(Name.s)
  SendNetworkString(ConnectionID,"NICK "+ReplaceString(Name, " ", "_")+Chr(13)+Chr(10))
EndProcedure

Procedure IRCJoin(Channel.s, Server.s)
  SendNetworkString(ConnectionID,"JOIN "+Channel+Chr(13)+Chr(10))
EndProcedure

Procedure IRCLeave(Channel.s)
  SendNetworkString(ConnectionID,"PART "+Channel+Chr(13)+Chr(10))
EndProcedure

Procedure IRCSendText(Channel.s, Text.s)
  SendNetworkString(ConnectionID,"PRIVMSG "+Channel+" :"+Text+Chr(13)+Chr(10))
EndProcedure

Procedure IRCSend(Text.s)
  SendNetworkString(ConnectionID,Text+Chr(13)+Chr(10))
EndProcedure

Procedure.s IRCGetFrom(Str.s)
  Start = FindString(Str.s, ":", 0)+1
  Stop = FindString(Str.s, "!", Start)
  ProcedureReturn Mid(Str.s, Start, Stop-Start)
EndProcedure

Procedure.s IRCGetTo(Str.s)
  Start = FindString(Str.s, "PRIVMSG", 2)+Len("PRIVMSG")+1
  Stop = FindString(Str.s, ":", Start)-1
  ProcedureReturn Mid(Str.s, Start, Stop-Start)
EndProcedure

Procedure.s IRCGetPingMsg(Str.s)
  Start = FindString(Str.s, ":", 0)+1
  Stop = Len(Str.s)+1
  ProcedureReturn Mid(Str.s, Start, Stop-Start)
EndProcedure

Procedure.s IRCGetLine()
   
  If NetworkClientEvent(ConnectionID) = 2
   
    LastElement(RecText())
    *Buffer = AllocateMemory(1024)
    ReceiveNetworkData(ConnectionID, *Buffer, 1024)
    
    txt.s = PeekS(*Buffer)
    FreeMemory(*Buffer)
    
    ReplaceString(txt, Chr(13), Chr(10))
    ReplaceString(txt, Chr(10)+Chr(10), Chr(10))
    
    For k=1 To CountString(txt, Chr(10))
      Line.s = RemoveString(RemoveString(StringField(txt, k, Chr(10)), Chr(10)), Chr(13))
      If Line <> ""
        If FindString(UCase(Line), "PING", 0) Or FindString(UCase(Line), "VERSION", 0)
           
          SendNetworkString(ConnectionID,ReplaceString(Line,"PING :", "PONG :",0)+Chr(13)+Chr(10))
        Else
          AddElement(RecText())
          RecText() = Line.s
        EndIf
      EndIf
    Next
  EndIf
   
  If ListSize(RecText()) > 0
    
    FirstElement(RecText())
    txt.s = RecText()
    DeleteElement(RecText())
  
    ProcedureReturn txt
  EndIf

EndProcedure

Procedure.s IRCGetText(Str.s)
  Start = FindString(Str.s, ":", FindString(Str.s, "PRIVMSG", 2)+Len("PRIVMSG"))
  
;   Parsed.s = Right(Str, Len(Str)-Start)
;   If Len(parsed) > 20
;    InsertString(parsed,Chr(13),20) 
;   EndIf
  
  ProcedureReturn Right(Str, Len(Str)-Start)
EndProcedure

Procedure.f IRCPing(Server.s, Timeout)
  *Buffer = AllocateMemory(1024)
  
  SendNetworkString(ConnectionID,"PING "+Server+Chr(13)+Chr(10))
  
  Time = ElapsedMilliseconds()
  While NetworkClientEvent(ConnectionID) <> 2 
    Delay(1) 
    If ElapsedMilliseconds()-Time > Timeout 
      Break 
    EndIf 
  Wend
  If ElapsedMilliseconds()-Time <= Timeout
    T = ElapsedMilliseconds()-Time
    ReceiveNetworkData(ConnectionID, *Buffer, 1024)
    FreeMemory(*Buffer)
    ProcedureReturn T/1000
  Else
    ProcedureReturn -1
  EndIf
EndProcedure

Procedure IRCDisconnect(Msg.s)  
  SendNetworkString(ConnectionID,"QUIT "+Msg.s+Chr(13)+Chr(10))
  CloseNetworkConnection(ConnectionID)
EndProcedure

Procedure.s IRCEnumNames(Channel.s) 
  
  SendNetworkString(ConnectionID,"NAMES "+Channel+Chr(13)+Chr(10))
  *Buffer = AllocateMemory(2048)
  
  While NetworkClientEvent(ConnectionID) <> 2 
    Delay(1) 
  Wend
  
  ReceiveNetworkData(ConnectionID, *Buffer, 2048)
   
  txt.s = PeekS(*Buffer)
  Debug txt.s
  FreeMemory(*Buffer)
  ;txt = ":irc.bierdopje.com 353 POEPTEST = #Bierdopje :POEPTEST +devixl ~Sypher 
  ;Sparky Lambiek12`pc +THC Ottacon &Vuurpijl %Jelpot|NY-party @Xandecs|SamSam blabla &MugenJin +Bierbot +Kiwi Fargh Icheb &dratone @Takkie @Born4Developing ~Wesley @Styxxy @Pimmetje +Orange 
  ;:irc.bierdopje.com 366 POEPTEST #bierdopje :End of /NAMES List.
  ;"
  Start = FindString(txt, ":"+Nick.s, 1)+Len(Nick.s)+1 ;306
  Stop = FindString(txt, ":"+Server.s+" 366", 1)
  
  ProcedureReturn Mid(txt.s, Start, Stop-Start)
EndProcedure

; Window Resizen :)
Procedure ResizeWin()
  ResizeGadget(1, 10, WindowHeight(0)-30, WindowWidth(0)-20, 20)
  ResizeGadget(0, 10, 10, WindowWidth(0)-170, WindowHeight(0)-50)
  ResizeGadget(2, WindowWidth(0)-160, 10, 150, WindowHeight(0)-50)
EndProcedure

; IDE Options = PureBasic 4.51 (Windows - x86)
; CursorPosition = 36
; FirstLine = 25
; Folding = ----
; EnableXP